<template>
  <div class="login-chat-test">
    <div class="test-container">
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <span>登录和聊天功能测试</span>
            <el-tag type="primary">完整测试</el-tag>
          </div>
        </template>

        <div class="test-content">
          <!-- 用户状态显示 -->
          <div class="user-status">
            <h3>当前用户状态</h3>
            <div v-if="userInfo" class="user-info">
              <el-tag type="success">已登录</el-tag>
              <span>用户ID: {{ userInfo.id }}</span>
              <span>邮箱: {{ userInfo.email }}</span>
              <span>角色: {{ getRoleName(userInfo.role) }}</span>
            </div>
            <div v-else class="user-info">
              <el-tag type="danger">未登录</el-tag>
              <el-button type="primary" @click="goToLogin">去登录</el-button>
            </div>
          </div>

          <!-- WebSocket连接状态 -->
          <div class="ws-status">
            <h3>WebSocket连接状态</h3>
            <div class="status-info">
              <el-tag :type="wsConnected ? 'success' : 'danger'">
                {{ wsConnected ? '已连接' : '未连接' }}
              </el-tag>
              <el-button 
                v-if="!wsConnected && userInfo" 
                type="primary" 
                @click="connectWebSocket"
                :loading="connecting"
              >
                连接WebSocket
              </el-button>
            </div>
          </div>

          <!-- 测试按钮区域 -->
          <div class="test-buttons">
            <h3>功能测试</h3>
            <div class="button-group">
              <el-button 
                type="primary" 
                @click="testLogin" 
                :loading="loading.login"
                :disabled="!!userInfo"
              >
                测试登录
              </el-button>
              
              <el-button 
                type="success" 
                @click="testChatSessions" 
                :loading="loading.sessions"
                :disabled="!userInfo"
              >
                获取聊天会话
              </el-button>
              
              <el-button 
                type="warning" 
                @click="testSystemMessages" 
                :loading="loading.systemMsg"
                :disabled="!userInfo"
              >
                获取系统消息
              </el-button>
              
              <el-button 
                type="info" 
                @click="testSendMessage" 
                :loading="loading.sendMsg"
                :disabled="!userInfo"
              >
                发送测试消息
              </el-button>
              
              <el-button 
                type="danger" 
                @click="logout"
                :disabled="!userInfo"
              >
                退出登录
              </el-button>
            </div>
          </div>

          <!-- 结果显示区域 -->
          <div class="results-section">
            <h3>测试结果</h3>
            <div v-if="results.length === 0" class="no-results">
              暂无测试结果，请点击上方按钮进行测试
            </div>
            <div v-for="(result, index) in results" :key="index" class="result-item">
              <div class="result-header">
                <span class="result-time">{{ result.time }}</span>
                <el-tag :type="result.success ? 'success' : 'danger'" size="small">
                  {{ result.test }}
                </el-tag>
                <el-tag :type="getStatusType(result.status)" size="small">
                  {{ result.status }}
                </el-tag>
              </div>
              <div class="result-details">
                <p><strong>描述:</strong> {{ result.description }}</p>
                <p><strong>响应:</strong></p>
                <pre class="json-display">{{ JSON.stringify(result.response, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  userLogin, 
  getChatSessions, 
  getSystemMessages, 
  sendChatMessage,
  createChatSession 
} from '@/utils/apiService'
import { getUserInfo, saveUserToken, saveUserInfo, userLogout } from '@/utils/auth'
import chatWebSocket from '@/utils/websocket'

const router = useRouter()

// 响应式数据
const userInfo = ref(null)
const wsConnected = ref(false)
const connecting = ref(false)
const loading = reactive({
  login: false,
  sessions: false,
  systemMsg: false,
  sendMsg: false
})

const results = ref([])

// 方法
const addResult = (test, description, status, response, success) => {
  results.value.unshift({
    time: new Date().toLocaleTimeString(),
    test,
    description,
    status,
    response,
    success
  })
  
  // 只保留最近10条结果
  if (results.value.length > 10) {
    results.value = results.value.slice(0, 10)
  }
}

const getStatusType = (status) => {
  if (status >= 200 && status < 300) return 'success'
  if (status >= 400 && status < 500) return 'warning'
  if (status >= 500) return 'danger'
  return 'info'
}

const getRoleName = (role) => {
  const roleMap = {
    1: '租客',
    2: '房东',
    4: '中介',
    8: '管理员'
  }
  return roleMap[role] || '未知'
}

// 测试登录
const testLogin = async () => {
  loading.login = true
  
  try {
    const response = await userLogin({
      email: '277849093@qq.com',
      password: 'Buyuyu777'
    })
    
    if (response.code === '200') {
      // 保存token和用户信息
      if (response.data.info) {
        saveUserToken(response.data.info)
      }
      if (response.data.loginUser) {
        saveUserInfo(response.data.loginUser)
        userInfo.value = response.data.loginUser
      }
      
      addResult(
        '用户登录',
        '使用测试账号登录',
        200,
        response,
        true
      )
      
      ElMessage.success('登录成功')
      
      // 自动连接WebSocket
      await connectWebSocket()
    } else {
      addResult(
        '用户登录',
        '登录失败',
        response.code,
        response,
        false
      )
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error) {
    console.error('登录测试失败:', error)
    addResult(
      '用户登录',
      '登录请求异常',
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('登录测试失败: ' + error.message)
  } finally {
    loading.login = false
  }
}

// 连接WebSocket
const connectWebSocket = async () => {
  if (!userInfo.value) {
    ElMessage.warning('请先登录')
    return
  }
  
  connecting.value = true
  
  try {
    await chatWebSocket.connect()
    wsConnected.value = true
    
    // 添加连接状态监听
    chatWebSocket.addConnectionHandler((connected) => {
      wsConnected.value = connected
    })
    
    addResult(
      'WebSocket连接',
      '连接聊天服务器',
      200,
      { connected: true },
      true
    )
    
    ElMessage.success('WebSocket连接成功')
  } catch (error) {
    console.error('WebSocket连接失败:', error)
    wsConnected.value = false
    
    addResult(
      'WebSocket连接',
      'WebSocket连接失败',
      'ERROR',
      { error: error.message },
      false
    )
    
    ElMessage.error('WebSocket连接失败: ' + error.message)
  } finally {
    connecting.value = false
  }
}

// 测试获取聊天会话
const testChatSessions = async () => {
  loading.sessions = true
  
  try {
    const response = await getChatSessions()
    
    addResult(
      '获取聊天会话',
      '获取用户的聊天会话列表',
      response.status || 200,
      response,
      response.code === '200'
    )
    
    if (response.code === '200') {
      ElMessage.success('获取聊天会话成功')
    } else {
      ElMessage.warning('获取聊天会话失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取聊天会话失败:', error)
    addResult(
      '获取聊天会话',
      '请求异常',
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('获取聊天会话失败: ' + error.message)
  } finally {
    loading.sessions = false
  }
}

// 测试获取系统消息
const testSystemMessages = async () => {
  loading.systemMsg = true
  
  try {
    const response = await getSystemMessages({ page: 1, size: 10 })
    
    addResult(
      '获取系统消息',
      '获取用户的系统消息列表',
      response.status || 200,
      response,
      response.code === '200'
    )
    
    if (response.code === '200') {
      ElMessage.success('获取系统消息成功')
    } else {
      ElMessage.warning('获取系统消息失败: ' + response.message)
    }
  } catch (error) {
    console.error('获取系统消息失败:', error)
    addResult(
      '获取系统消息',
      '请求异常',
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('获取系统消息失败: ' + error.message)
  } finally {
    loading.systemMsg = false
  }
}

// 测试发送消息
const testSendMessage = async () => {
  loading.sendMsg = true
  
  try {
    // 先创建一个测试会话
    const sessionResponse = await createChatSession({
      targetUserId: 2, // 假设目标用户ID为2
      houseId: 1 // 假设房源ID为1
    })
    
    if (sessionResponse.code === '200') {
      // 发送测试消息
      const messageResponse = await sendChatMessage({
        receiverId: 2,
        content: '这是一条测试消息，发送时间: ' + new Date().toLocaleString(),
        type: 1
      })
      
      addResult(
        '发送消息',
        '发送测试聊天消息',
        messageResponse.status || 200,
        messageResponse,
        messageResponse.code === '200'
      )
      
      if (messageResponse.code === '200') {
        ElMessage.success('发送消息成功')
      } else {
        ElMessage.warning('发送消息失败: ' + messageResponse.message)
      }
    } else {
      addResult(
        '发送消息',
        '创建会话失败',
        sessionResponse.status || 400,
        sessionResponse,
        false
      )
      ElMessage.error('创建会话失败: ' + sessionResponse.message)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    addResult(
      '发送消息',
      '请求异常',
      'ERROR',
      { error: error.message },
      false
    )
    ElMessage.error('发送消息失败: ' + error.message)
  } finally {
    loading.sendMsg = false
  }
}

// 退出登录
const logout = () => {
  userLogout()
  userInfo.value = null
  wsConnected.value = false
  chatWebSocket.disconnect()
  
  addResult(
    '退出登录',
    '用户退出登录',
    200,
    { success: true },
    true
  )
  
  ElMessage.success('退出登录成功')
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 初始化
const init = () => {
  userInfo.value = getUserInfo()
  if (userInfo.value) {
    connectWebSocket()
  }
}

// 生命周期
onMounted(() => {
  init()
})

onBeforeUnmount(() => {
  chatWebSocket.disconnect()
})
</script>

<style scoped>
.login-chat-test {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.test-container {
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  color: #2c3e50;
}

.test-content {
  padding: 20px 0;
}

.user-status, .ws-status, .test-buttons, .results-section {
  margin-bottom: 30px;
}

.user-status h3, .ws-status h3, .test-buttons h3, .results-section h3 {
  color: #409eff;
  margin-bottom: 15px;
}

.user-info, .status-info {
  display: flex;
  gap: 15px;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.no-results {
  text-align: center;
  color: #909399;
  padding: 40px;
  background: #f8f9fa;
  border-radius: 8px;
}

.result-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.result-header {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.result-time {
  font-size: 12px;
  color: #909399;
}

.result-details p {
  margin: 10px 0;
  color: #2c3e50;
}

.json-display {
  background: #2c3e50;
  color: #fff;
  padding: 15px;
  border-radius: 6px;
  font-size: 12px;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  margin: 5px 0;
}
</style>
